package com.google.code.mochaccino.framework.transaction;
/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.google.code.mochaccino.framework.transaction.exception.TransactionManagementException;
import com.google.code.mochaccino.framework.transaction.exception.TransactionRequiredException;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.Synchronization;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import org.aspectj.lang.ProceedingJoinPoint;

/**
 * TransactionManagerFacade wraps the JTA Transaction Manager and provides a simplified APIs for the Aspect Implementation
 * for the Transaction Management.
 */
public final class TransactionManagerImpl implements TransactionManager {

	private javax.transaction.TransactionManager jta = null;

	/** Constructor */
	public TransactionManagerImpl( javax.transaction.TransactionManager mgr ) {
		this.jta = mgr;
	}

	/**
	 * Handle a requires new transaction rqeuest. If there is an existing transaction, it
	 * will suspend it, start a new one, proceed and resume previous transaction afterwards.
	 */
	public Object handleRequiresNew( ProceedingJoinPoint jp ) throws Throwable {
		Transaction suspendedTransaction = jta.suspend();
		try {
			return handleRequired( jp );
		} finally {
			if ( suspendedTransaction != null ) {
				jta.resume( suspendedTransaction );
			}
		}
	}

	/**
	 * Handle a required transaction request. If the point-cut throws an exception, it will
	 * automatically rollback
	 */
	public Object handleRequired( ProceedingJoinPoint jp ) throws Throwable {
		Transaction trx = null;
		try {
			jta.begin();
			trx = jta.getTransaction();
			Object result = handleMandatory( jp );
			trx.commit();
			return result;
		} catch ( Throwable t ) {
			if ( trx != null ) {
				trx.rollback();
			}
			throw t;
		}
	}

	public Object handle( Propagation propagation, ProceedingJoinPoint jp ) throws Throwable {

		verifyTransactionState( propagation );

		if ( propagation == Propagation.MANDATORY ) {
			return handleMandatory( jp );
		} else if ( propagation == Propagation.REQUIRED ) {
			return handleRequired( jp );
		} else if ( propagation == Propagation.REQUIRES_NEW ) {
			return handleRequiresNew( jp );
		} else if ( propagation == Propagation.SUPPORTS ) {
			return handleSupports( jp );
		}
		throw new UnsupportedOperationException( "Unknown Propagation :" + propagation.name() );
	}

	/**
	 * Handle a Mandatory Transaction Request. If no transaction was present should not
	 * have been reached per implementation.
	 */
	public Object handleMandatory( ProceedingJoinPoint jp ) throws Throwable {
		return jp.proceed( jp.getArgs() );
	}

	public Object handleSupports( ProceedingJoinPoint jp ) throws Throwable {
		return jp.proceed( jp.getArgs() );
	}

	@Override
	public boolean isStarted() {
		try {
			return jta.getStatus() == Status.STATUS_ACTIVE;
		} catch ( SystemException e ) {
			return false;
		}
	}

	public boolean registerListener( final TransactionListener sync ) throws TransactionManagementException {
		Transaction trx = null;
		try {
			trx = jta.getTransaction();

			if ( trx != null ) {
				trx.registerSynchronization( new Synchronization() {

					@Override
					public void beforeCompletion() {
						sync.beforeCompletion();
					}

					@Override
					public void afterCompletion( int status ) {
						sync.afterCompletion( TransactionStatus.getForStatusCode( status ) );
					}
				} );
				return true;
			}
			return false;
		} catch ( SystemException e ) {
			throw new TransactionManagementException( e );
		} catch ( RollbackException e ) {
			throw new TransactionManagementException( e );
		}
	}

	/** Validate the transaction state agaisnt the transactional requirements */
	public void verifyTransactionState( Propagation requirements ) throws TransactionManagementException, TransactionRequiredException {
		if ( requirements == Propagation.SUPPORTS ) {
			verifyTransactionSupports();
			return;
		}

		if ( requirements == Propagation.MANDATORY ) {
			verifyTransactionStateMandatory();
			return;
		}

		if ( requirements == Propagation.REQUIRED ) {
			verifyTransactionStateRequired();
			return;
		}

		if ( requirements == Propagation.REQUIRES_NEW ) {
			verifyTransactionStateRequiresNew();
			return;
		}
	}

	/** Validate the transaction state agaisnt the transactional requirements */
	protected void verifyTransactionStateMandatory() throws TransactionManagementException, TransactionRequiredException {
		try {
			int status = jta.getStatus();
			if ( status == Status.STATUS_NO_TRANSACTION ||
			     status == Status.STATUS_MARKED_ROLLBACK ||
			     status == Status.STATUS_PREPARED ||
			     status == Status.STATUS_PREPARING ||
			     status == Status.STATUS_ROLLEDBACK ||
			     status == Status.STATUS_ROLLING_BACK ||
			     status == Status.STATUS_UNKNOWN ) {
				throw new TransactionRequiredException( "No Active Transaction (or invalid transaction status): " + TransactionStatus.getForStatusCode( status ).name() );
			}
		} catch ( SystemException e ) {
			throw new TransactionManagementException( e );
		}
	}

	/** Validate the transaction state agaisnt the transactional requirements */
	protected void verifyTransactionStateRequired() throws TransactionManagementException, TransactionRequiredException {
		try {
			int status = jta.getStatus();
			if ( status == Status.STATUS_MARKED_ROLLBACK ||
			     status == Status.STATUS_COMMITTED ||
			     status == Status.STATUS_COMMITTING ||
			     status == Status.STATUS_PREPARED ||
			     status == Status.STATUS_PREPARING ||
			     status == Status.STATUS_ROLLEDBACK ||
			     status == Status.STATUS_ROLLING_BACK ||
			     status == Status.STATUS_UNKNOWN ) {
				throw new TransactionRequiredException( "Active Transaction detected (or invalid transaction status): " + TransactionStatus.getForStatusCode( status ).name() );
			}
		} catch ( SystemException e ) {
			throw new TransactionManagementException( e );
		}
	}

	/** Validate the transaction state agaisnt the transactional requirements */
	protected void verifyTransactionStateRequiresNew() throws TransactionManagementException, TransactionRequiredException {

	}

	/** Validate the supports propagation mode. */
	protected void verifyTransactionSupports() {

	}
}
